package com.qf.ssm.pay.controller;

import com.qf.ssm.pay.pojo.Orders;
import com.qf.ssm.pay.pojo.ResponseResult;
import com.qf.ssm.pay.service.MerchantService;
import com.qf.ssm.pay.service.OrdersService;
import com.qf.ssm.pay.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private OrdersService ordersService;

    @RequestMapping("/create")
    @ResponseBody
    public ResponseResult create(Orders orders, String sign) {
        ResponseResult responseResult = new ResponseResult();
        //验证参数不为空略
        //md5(orderId=xxx&price=xxxx&merchantId=xxx&notifyURL=xxxx&otherParam=xxx+secretKey)
        StringBuilder sb = new StringBuilder();
        sb.append("orderId=").append(orders.getOrderId());
        sb.append("price=").append(orders.getPrice());
        sb.append("merchantId=").append(orders.getMerchantId());
        sb.append("notifyURL=").append(orders.getNotifyURL());
        sb.append("otherParam=");
        if (!StringUtils.isEmpty(orders.getOtherParam())) {
            sb.append(orders.getOtherParam());
        }
        String secretKey = merchantService.getScretKeyById(orders.getMerchantId());
        sb.append(secretKey);
        //自己计算出的签名
        String signStr = MD5Util.getMD5(sb.toString());
        System.out.println(signStr);
        if (sign.equals(signStr)) {
            //按照指定算法计算签名如果签名正确，添加订单
            String tradeNum = "qfpay" + System.currentTimeMillis();
            orders.setTradeNum(tradeNum);
            ordersService.addOrder(orders);
            responseResult.setMessage("创建订单成功");
            responseResult.setResultCode("0001");
            responseResult.setOther(orders);
        } else {
            responseResult.setSuccess(false);
            responseResult.setResultCode("0000");
            responseResult.setMessage("签名错误");
        }
        return responseResult;
    }
}
